home *** CD-ROM | disk | FTP | other *** search
- Path: news.primenet.com!not-for-mail
- From: gbe@primenet.com (Gary Edstrom)
- Newsgroups: comp.lang.c++
- Subject: Re: [Q] new-allocated objects within try block
- Date: 20 Jan 1996 15:51:01 -0700
- Organization: Sequoia Software
- Sender: root@primenet.com
- Message-ID: <31016b0a.148193273@news.primenet.com>
- References: <monnet-2001962147210001@alpnet76.alpes-net.fr>
- X-Posted-By: ip059.lax.primenet.com
- X-Newsreader: Forte Agent .99c/16.141
-
- Here is a way of handling your problem using an intermediate helper
- class. With this approach, you don't need to worry about executing
- the new/delete operators.
-
- class ABC { public: virtual void DoSomething() = 0; };
- class A : public ABC { public: virtual void DoSomething(); };
- class B : public ABC { public: virtual void DoSomething(); };
-
- class Q
- {
- private:
- ABC * ptr;
- public:
- void DoSomething() { ptr->DoSomething(); }
-
- Q(test) { if (test) ptr = new A; else ptr = new B; }
- ~Q() { delete ptr; }
- };
-
- Now, here is your modified try/catch block:
-
- try {
- Q p(test);
- ...
- throw sthg;
- ...
- p.DoSomething();
- }
- catch (...) { ... }
-
- Using this approach, the destructor for Q will be executed
- automatically after the program hits the "throw" statement. Also
- notice that the arrow notation has been changed to a dot notation. To
- as great a degree as possible, I try to follow the convention of only
- using "new" operators inside constructors and "delete" operators
- inside destructors.
-
- Gary Edstrom <gbe@primenet.com>
-
- --
- Gary Edstrom <gbe@primenet.com> | Sequoia Software
- PO Box 9573 | Programming & Technical Services
- Glendale CA 91226-0573 | PGP Key ID: 0x1A0D44BD
- PGP Fingerprint: 72 AA 4F 73 05 53 89 C6 8A EE F4 EE D1 C0 13 8D
-